package com.example.myapplication.homesosuo;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatEditText;

import com.example.myapplication.R;

public class EditText_Clear extends AppCompatEditText {

    private Drawable clearDrawable,searchDrawable;
    private Drawable ClearDrawable;

    public EditText_Clear(Context context) {
        super(context);
        init();
    }
public EditText_Clear(Context context, AttributeSet attrs){
        super(context,attrs);
        init();
}
    private void init() {
        ClearDrawable = getResources().getDrawable(R.drawable.ic_launcher_background);
        searchDrawable = getResources().getDrawable(R.drawable.ic_launcher_background);

        setCompoundDrawablesWithIntrinsicBounds(searchDrawable,null,null,null);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start,int lengthBefore, int lengthAfrer){
        super.onTextChanged(text,start,lengthBefore,lengthAfrer);
        setClearIconVisible(hasFocus() && text.length() > 0);
        // hasFocus()返回是否获得EditTEXT的焦点，即是否选中
        // setClearIconVisible（） = 根据传入的是否选中 & 是否有输入来判断是否显示删除图标
    }
    @Override
    protected  void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        setClearIconVisible(focused && length() > 0);
        // focused = 是否获得焦点
        // 同样根据setClearIconVisible（）判断是否要显示删除图标
    }
    private void setClearIconVisible(boolean visible){
        setCompoundDrawablesWithIntrinsicBounds(searchDrawable, null,visible ? clearDrawable : null,null);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event){
        switch (event.getAction()){
            case MotionEvent.ACTION_UP:
                Drawable drawable = clearDrawable;
                if(drawable != null && event.getX() <=(getWidth() - getPaddingRight())
                && event.getX() >= (getWidth() - getPaddingRight()-drawable.getBounds().width())){
                    setText("");
                }
                break;
        }
        return super.onTouchEvent(event);
    }

}
